package queue;

import java.util.Iterator;

public class ArrayQueue4<E> implements Queue<E>, Iterable<E> {
    private int head;
    private int tail;
    private E[] array;

    public ArrayQueue4(int capacity) {
        /**
         *  第一种直接抛异常
         if ((capacity & capacity - 1) != 0) { // 2的指数 与 2的指数-1 按位与为0     1000  0111
         throw new IllegalArgumentException("数组长度必须为2的指数");
         }
         **/
        // 求离capacity最近 比capacity大的2的n次方的数方法1
        int n = (int) ((Math.log10(capacity - 1) / Math.log10(2)) + 1); // -1 是为了当为2的指数本身 例如32为变成64
        array = (E[]) new Object[1 << n];

        // 求离capacity最近 比capacity大的2的n次方的数方法2
        capacity -= 1;
        capacity |= capacity >> 1;
        capacity |= capacity >> 2;
        capacity |= capacity >> 4;
        capacity |= capacity >> 8;
        capacity |= capacity >> 16;
        capacity += 1;
    }

    @Override
    public Iterator<E> iterator() {
        return null;
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        array[tail & array.length - 1] = value;
        tail++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E val = array[head & array.length - 1];
        head++;
        return val;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[head & array.length - 1];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return false;
    }
}
